package com.liser.print.bluetooth.receiver;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import com.liser.print.bluetooth.callback.BaseCallback;

/**
 * 蓝牙扫描广播
 *
 * @author LISER
 * @date 2020/01/14
 */
public class BtScanReceiver extends BroadcastReceiver {

    /**
     * 扫描设备回调
     */
    private BaseCallback baseCallback;

    public BtScanReceiver(Context context, BaseCallback baseCallback) {
        this.baseCallback = baseCallback;
        IntentFilter filter = new IntentFilter();

        //蓝牙开始搜索
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        //蓝牙搜索结束
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        //蓝牙发现新设备(未配对)
        filter.addAction(BluetoothDevice.ACTION_FOUND);

        context.registerReceiver(this, filter);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        BluetoothDevice dev;
        if (action == null) {
            return;
        }
        switch (action) {
            // 蓝牙开始搜索
            case BluetoothAdapter.ACTION_DISCOVERY_STARTED:
                baseCallback.onScanStart();
                break;

            // 蓝牙搜索结束
            case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
                baseCallback.onScanStop();
                break;

            // 发现新设备
            case BluetoothDevice.ACTION_FOUND:
                dev = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                baseCallback.onFindDevice(dev);
                break;
            default:
                break;
        }
    }
}